package com.fanrenqiji.modules.sys.web;

import com.fanrenqiji.common.config.GlobalSetting;
import com.fanrenqiji.common.web.BaseController;
import com.fanrenqiji.modules.sys.entity.Menu;
import com.fanrenqiji.modules.sys.service.SystemService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletResponse;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @author lijian E-mail:ljz0721cx@163.com
 * @version 创建时间：2015年1月30日 下午3:26:41
 * @description 系统菜单控制类
 */
@Controller
@RequestMapping(value={"${adminPath}/sys/menu"})
public class MenuController extends BaseController{

	@Autowired
	private SystemService systemService;

	/**
	 * 菜单Model
	 * 
	 * @param id
	 * @return
	 */
	@ModelAttribute("menu")
	public Menu get(@RequestParam(required = false) Long id) {
		if (id != null) {
			return systemService.getMenu(id);
		} else {
			return new Menu();
		}
	}

	/**
	 * 获得左侧的菜单列表
	 * 
	 * @return
	 */
	@RequiresUser
	@RequestMapping(value = "tree")
	public String tree() {
		return "modules/sys/menuTree";
	}

	/**
	 * 在有model时候加载资源 获得权限列表
	 * 
	 * @param model
	 * @return
	 */
	@RequiresPermissions("sys:menu:view")
	@RequestMapping(value = { "list", "" })
	public String list(Model model) {
		List<Menu> list = Lists.newArrayList();
		List<Menu> sourcelist = systemService.findAllMenu();
		Menu.sortList(list, sourcelist, 1L);
		model.addAttribute("list", list);
		return "modules/sys/menuList";
	}
	/**
	 * 批量修改菜单排序
	 */
	@RequiresPermissions("sys:menu:edit")
	@RequestMapping(value = "updateSort")
	public String updateSort(Long[] ids, Integer[] sorts, RedirectAttributes redirectAttributes) {
    	int len = ids.length;
    	Menu[] menus = new Menu[len];
    	for (int i = 0; i < len; i++) {
    		menus[i] = systemService.getMenu(ids[i]);
    		menus[i].setSort(sorts[i]);
    		systemService.saveMenu(menus[i]);
    	}
    	addMessage(redirectAttributes, "保存菜单排序成功!");
		return "redirect:"+GlobalSetting.getAdminPath()+"/sys/menu/";
	}
	/**
	 * 提交用户选择的菜单
	 * @param menu
	 * @param model
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions(value="sys:menu:edit")
	@RequestMapping(value="save")
	public String save(Menu menu, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, menu)){
			return form(menu, model);
		}
		systemService.saveMenu(menu);
		addMessage(redirectAttributes, "保存菜单'" + menu.getName() + "'成功");
		return "redirect:"+GlobalSetting.getAdminPath()+"/sys/menu/";
	}
	/**
	 * 删除菜单以及删除下级菜单
	 * @param menu
	 * @param model
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions(value="sys:menu:edit")
	@RequestMapping(value="delete")
	public String delete(Long id, RedirectAttributes redirectAttributes) {
		if (Menu.isRoot(id)){
			addMessage(redirectAttributes, "删除菜单失败, 不允许删除顶级菜单或编号为空");
		}else{
			systemService.deleteMenu(id);
			addMessage(redirectAttributes, "删除菜单成功");
		}
		return "redirect:"+GlobalSetting.getAdminPath()+"/sys/menu/";
	}
	/**
	 * 到菜单的修改和编辑的form
	 * 
	 * @param menu
	 * @param model
	 * @return
	 */
	@RequiresPermissions("sys:menu:view")
	@RequestMapping(value = "form")
	public String form(Menu menu, Model model) {
		if (menu.getParent() == null || menu.getParent().getId() == null) {
			menu.setParent(new Menu(1L));
		}
		menu.setParent(systemService.getMenu(menu.getParent().getId()));
		model.addAttribute("menu", menu);
		return "modules/sys/menuForm";
	}
	/**
	 * 生成需要选择的菜单树
	 * @param extId
	 * @param response
	 * @return
	 */
	@RequiresUser
	@ResponseBody
	@RequestMapping(value = "treeData")
	public List<Map<String, Object>> treeData(
			@RequestParam(required = false) Long extId,
			HttpServletResponse response) {
		response.setContentType("application/json; charset=UTF-8");
		List<Map<String, Object>> mapList = Lists.newArrayList();
		List<Menu> list = systemService.findAllMenu();
		Iterator<Menu> it = list.iterator();
		while (it.hasNext()) {
			Menu e = it.next();
			/**
			 * 排除menu 
			 * 如果排除的menu为空   
			 * 或者排出的menu不为空并且排出的menu等于当前的menu和所有的父级菜单中没有对应的值
			 */
			if (extId == null
					|| (extId != null && !extId.equals(e.getId()) && e
							.getParentIds().indexOf("," + extId + ",") == -1)) {
				Map<String, Object> map = Maps.newHashMap();
				map.put("id", e.getId());
				map.put("pId", e.getParent() != null ? e.getParent().getId(): 0);
				map.put("name", e.getName());
				mapList.add(map);
			}
		}
		return mapList;
	}

}
